package krow.dev.contest;

import krow.dev.contest.Constants.Invoke;
import krow.dev.contest.controller.SubcategoryFactory;
import krow.dev.contest.model.SubcategoryItem;
import krow.dev.contest.view.SubcategoryListAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

public class SubcategoryFragment extends Fragment {
	
	private SubcategoryListAdapter mSubcategoryListAdapter;
	private ListView mSubcategoryListView;
	private String mCategory;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		Bundle arguments = getArguments();
		if(arguments != null){
			mCategory = arguments.getString(Invoke.KEY_CATEGORY);
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		
		View view = inflater.inflate(R.layout.fragment_categorylist, null);

		SubcategoryFactory subcategoryFactory = new SubcategoryFactory(getActivity());
		mSubcategoryListAdapter = new SubcategoryListAdapter(getActivity());
		mSubcategoryListAdapter.setSubcategoryItemList(subcategoryFactory.createCategoryList(mCategory));
		mSubcategoryListView = (ListView) view.findViewById(R.id.list_subcategory);
		mSubcategoryListView.addFooterView(inflater.inflate(R.layout.footer_dummy, null));
		mSubcategoryListView.setAdapter(mSubcategoryListAdapter);
		mSubcategoryListView.setOnItemClickListener(mSubItemClickListener);
		
		return view;
	}
	
	private AdapterView.OnItemClickListener mSubItemClickListener = new AdapterView.OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			if (view.getTag() == null) {
				return;
			}
			
			SubcategoryItem subcategoryItem = (SubcategoryItem) view.getTag();
			
			StringBuilder urlBuilder = new StringBuilder();
			urlBuilder.append("http://rss.campusmon.com/contest_");
			urlBuilder.append(subcategoryItem.getCategory());
			urlBuilder.append(subcategoryItem.getId());
			urlBuilder.append(".xml");
			
			System.out.println(urlBuilder.toString());
		
			Intent intent = new Intent(getActivity(), ContestListActivity.class);
			intent.putExtra(Invoke.KEY_TITLE, subcategoryItem.getName());
			intent.putExtra(Invoke.KEY_URL, urlBuilder.toString());
			
			startActivity(intent);
			
			getActivity().overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
		}
	};
	
}
